package org.jeecg.modules.zcgl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgBaseController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.zcgl.entity.StatementAccount;
import org.jeecg.modules.zcgl.entity.StatementAccountDetails;
import org.jeecg.modules.zcgl.service.IStatementAccountDetailsService;
import org.jeecg.modules.zcgl.service.IStatementAccountService;
import org.jeecg.modules.zcgl.vo.StatementAccountPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 对账单信息
 * @Author: jeecg-boot
 * @Date: 2021-01-15
 * @Version: V1.0
 */
@Api(tags = "对账单信息")
@RestController
@RequestMapping("/zcgl/statementAccount")
@Slf4j
public class StatementAccountController extends JeecgBaseController<StatementAccountPage, StatementAccount, IStatementAccountService> {
    @Autowired
    private IStatementAccountService statementAccountService;
    @Autowired
    private IStatementAccountDetailsService statementAccountDetailsService;
    @Autowired
    private ISysDepartService departService;

    /**
     * 分页列表查询
     *
     * @param statementAccount
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "对账单信息-分页列表查询")
    @ApiOperation(value = "对账单信息-分页列表查询", notes = "对账单信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(StatementAccount statementAccount,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<StatementAccount> queryWrapper = QueryGenerator.initQueryWrapper(statementAccount, req.getParameterMap());
        Page<StatementAccount> page = new Page<StatementAccount>(pageNo, pageSize);
        IPage<StatementAccount> pageList = statementAccountService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param statementAccountPage
     * @return
     */
    @AutoLog(value = "对账单信息-添加")
    @ApiOperation(value = "对账单信息-添加", notes = "对账单信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody StatementAccountPage statementAccountPage) {
        StatementAccount statementAccount = new StatementAccount();
        BeanUtils.copyProperties(statementAccountPage, statementAccount);
        statementAccountService.saveOrUpdateMain(statementAccount, statementAccountPage.getStatementAccountDetailsList());
        return Result.ok("添加成功！");
    }

    /**
     * 手动下载对账单
     *
     * @param statementAccount
     * @return
     */
    @AutoLog(value = "对账单信息-手动下载对账单")
    @ApiOperation(value = "对账单信息-添加", notes = "对账单信息-手动下载对账单")
    @PostMapping(value = "/downloadStatementAccount")
    public Result<?> downloadStatementAccount(@RequestBody StatementAccount statementAccount) {
        if (statementAccount.getDate() == null){
            return Result.errorValidation("请选择需要下载对账单的日期！");
        }
        if (DateUtils.sameDate(statementAccount.getDate(), DateUtils.getDate()) >= 0){
            return Result.errorValidation("需要下载对账单的日期必须小于当前日期！");
        }
        List<SysDepart> list = new ArrayList<>();
        LoginUser loginUser = JwtUtil.getLoginUser();
        if (StringUtils.isNotBlank(statementAccount.getCompanyId())){
            list.add(departService.getById(statementAccount.getCompanyId()));
        } else if (loginUser.getCurrentCompanyId().equalsIgnoreCase(jeecgPropertyConfig.getBaseDepartId())){
            list.addAll(departService.queryCompanyList());
        } else {
            list.add(departService.getById(loginUser.getCurrentCompanyId()));
        }

        List<String> errorMessage = new ArrayList<>();
        list.stream().forEach(depart -> {
            try {
                statementAccountService.statementAccountByDepart(depart, statementAccount.getDate());
            } catch (JeecgBootException e) {
//                    e.printStackTrace();
//                log.error(depart.getDepartName() + "对账单下载失败！" + e.getMessage());
                errorMessage.add(depart.getDepartName() + "对账单下载失败：【" + e.getMessage() + "】");
            } catch (Exception e){
                errorMessage.add(depart.getDepartName() + "对账单下载失败！");
            }
        });
        if (errorMessage.size() == 0){
            return Result.ok("下载成功！");
        } if (errorMessage.size() < list.size()){
            return Result.error("部分下载失败：" + StringUtils.join(errorMessage, CommonConstant.DEFAULT_SEPARATOR));
        } else {
            return Result.error("下载失败：" + StringUtils.join(errorMessage, CommonConstant.DEFAULT_SEPARATOR));
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "对账单信息-通过id删除")
    @ApiOperation(value = "对账单信息-通过id删除", notes = "对账单信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        statementAccountService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "对账单信息-批量删除")
    @ApiOperation(value = "对账单信息-批量删除", notes = "对账单信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.statementAccountService.delBatchMain(Arrays.asList(ids.split(CommonConstant.DEFAULT_SEPARATOR)));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "对账单信息-通过id查询")
    @ApiOperation(value = "对账单信息-通过id查询", notes = "对账单信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        StatementAccount statementAccount = statementAccountService.getById(id);
        if (statementAccount == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(statementAccount);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "对账单详情-通过主表ID查询")
    @ApiOperation(value = "对账单详情-通过主表ID查询", notes = "对账单详情-通过主表ID查询")
    @GetMapping(value = "/queryStatementAccountDetailsByMainId")
    public Result<?> queryStatementAccountDetailsListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<StatementAccountDetails> statementAccountDetailsList = statementAccountDetailsService.selectByMainId(id);
        IPage<StatementAccountDetails> page = new Page<>();
        page.setRecords(statementAccountDetailsList);
        page.setTotal(statementAccountDetailsList.size());
        return Result.ok(page);
    }

    /**
     * 通过主表ID分页查询
     *
     * @param details
     * @return
     */
    @AutoLog(value = "对账单详情-通过主表ID分页查询")
    @ApiOperation(value = "对账单详情-通过主表ID分页查询", notes = "对账单详情-通过主表ID分页查询")
    @GetMapping(value = "/queryStatementAccountDetailsPage")
    public Result<?> queryStatementAccountDetailsPageList(
            StatementAccountDetails details,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<StatementAccountDetails> queryWrapper = new QueryWrapper<>(details);
        Page<StatementAccountDetails> page = new Page<>(pageNo, pageSize);
        IPage<StatementAccountDetails> pageList = statementAccountDetailsService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param statementAccount
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StatementAccount statementAccount) {
        return super.exportXls(request, statementAccount, StatementAccountPage.class, "对账单信息数据");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, StatementAccountPage.class);
    }

    @Override
    public List<StatementAccountPage> exportList(List<StatementAccount> list) {
        return new ArrayList<>();
    }

    @Override
    public boolean importSave(StatementAccountPage statementAccountPage) {
        return false;
    }
}
